package com.alliky.core.net;

import com.alliky.core.api.BaseApi;
import com.alliky.core.BuildConfig;
import com.alliky.core.config.Config;
import com.alliky.core.net.converter.CustomConverterFactory;
import com.alliky.core.net.interceptors.BodyInterceptor;
import com.alliky.core.net.interceptors.CacheInterceptor;
import com.alliky.core.net.interceptors.LogInterceptor;
import com.alliky.core.net.interceptors.RequestParameterInterceptor;
import com.alliky.core.net.interceptors.logger.Level;
import com.alliky.core.net.interceptors.logger.LoggingInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RxRetrofit {

    private static Retrofit mInstance = null;

    public static Retrofit getInstance() {
        if (mInstance == null) {
            synchronized (RxRetrofit.class) {
                if (mInstance == null) {
                    mInstance = new Retrofit.Builder()
                            .baseUrl(BaseApi.API_HOST)
                            .client(getOkHttpClient())
                            .addConverterFactory(CustomConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }
        return mInstance;
    }

    private static OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        Level level = Level.NONE;
        if (BuildConfig.DEBUG) {
            level = Level.BODY;
        }
        LoggingInterceptor mLoggingInterceptor = new LoggingInterceptor
                .Builder()//构建者模式
                .loggable(true) //是否开启日志打印
                .setLevel(level) //打印的等级
                .log(Platform.INFO) // 打印类型
                .request("Request") // request的Tag
                .response("Response")// Response的Tag
                .addHeader("version", BuildConfig.VERSION_NAME)//打印版本
                .build();


        RequestParameterInterceptor requestParameterInterceptor = new RequestParameterInterceptor.Builder().build();
        builder.addInterceptor(requestParameterInterceptor);
        builder.addInterceptor(mLoggingInterceptor);

        builder.addInterceptor(new BodyInterceptor());
        builder.addInterceptor(new LogInterceptor());
        builder.addInterceptor(new CacheInterceptor(Config.getApplicationContext()));
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.writeTimeout(15, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        return builder.build();
    }
}
